package com.hotcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: huangzhigao
 * @Date: 2023/2/25 11:00
 */
public class leecode22 {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        backtrace(res, new StringBuilder(), 0, 0, n);
        return res;
    }


    public void backtrace(List<String> res, StringBuilder stringBuilder, int open, int close, int max) {
        if (stringBuilder.length() == max * 2) {
            res.add(stringBuilder.toString());
            return;
        }

        if (open < max) {
            stringBuilder.append("(");
            backtrace(res, stringBuilder, open + 1, close, max);
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }

        if (close < open) {
            stringBuilder.append(")");
            backtrace(res, stringBuilder, open, close + 1, max);
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
    }
}
